﻿using Microsoft.EntityFrameworkCore;
using NLog;
using NLog.Web;
using OpenAi.Util.Extensions;
using OpenAiProxy.API.Database;
using OpenAiProxy.API.Services;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;

var configFile = Path.Combine("Config", "NLog.config");
var logger = LogManager.Setup().LoadConfigurationFromFile(configFile).GetCurrentClassLogger();
logger.Warn("Program startup.");

var builder = WebApplication.CreateBuilder(args);

//使用NLog
builder.WebHost.ConfigureLogging(logging =>
    {
        logging.ClearProviders();
        logging.SetMinimumLevel(LogLevel.Trace);
        logging.AddConsole();
    })
    .UseNLog(); // NLog: Setup NLog for Dependency injection

// Add services to the container.

//添加NewtonsoftJson支持
builder.Services.AddControllers().AddNewtonsoftJson();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//注入服务
builder.Services.AddScoped<IHttpService, HttpService>();
builder.Services.AddSingleton<IConfigService, ConfigService>();

//注册数据库上下文(启用数据库连接池)
var connectionString = builder.Configuration.GetConnectionString("MySqlConnection");
builder.Services.AddPooledDbContextFactory<MySqlDbContext>(optionsBuilder =>
    optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)), 64);

//扫描profile文件
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

//初始化配置服务
var configService = app.Services.GetService<IConfigService>();
configService?.Init(builder.Configuration);

try
{
    await app.RunAsync();
}
catch (Exception exception)
{
    //NLog: catch setup errors
    logger.Error($"Stopped program because of exception: {exception.GetFullMessage()}.");
}
finally
{
    logger.Warn("Program shutdown.");

    // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
    LogManager.Shutdown();
}
